package com.mycompany.sudoku.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Grid;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SudokuUI implements EntryPoint {
	private Button generateButton;

	public void onModuleLoad() {
		RootPanel rootPanel = RootPanel.get();

		generateButton = new Button();
		rootPanel.add(generateButton, 297, 58);
		generateButton.setSize("130px", "28px");
		generateButton.setText("Generate");

		final Grid grid = new Grid(9, 9);
		grid.setBorderWidth(1);
		rootPanel.add(grid, 37, 58);
		grid.setSize("180", "180");

		// Create a reference to the SudokuGenServer
		final SudokuGenServiceAsync sudokuService = SudokuGenService.Util
				.getInstance();

		final AsyncCallback<int[][]> callback = new AsyncCallback<int[][]>() {
			public void onSuccess(int[][] result) {
				// Fill In the Grid
				for (int row=0; row<9 ; row++) {
					for (int col=0; col<9; col++){
					   int value=result[row][col];	
					   
					   if (value>0)
						   grid.setText(row, col, Integer.toString(value));
					}
				}
			}

			public void onFailure(Throwable caught) {
				// do some UI stuff to show failure
				Window.alert("Call to sudokuService Failed.");
			}

		};
		

		generateButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Window.alert("Generating Puzle...");

				sudokuService.generateGrid(0, callback);
			}
		});

	}
}
